/**
 * 完成路由、controller、service的注册服务
 */
import * as Router from 'koa-router';
import scanFileName from './utils/scanFileName';

const route = new Router();

export interface RegisterProps {
    routerPath: string;
    controllerPath: string;
    servicePath: string;
}

export default class {
    public route: any = route;
    private props: RegisterProps;
    private service: any;
    private controller: any = {};
    constructor(props: RegisterProps) {
        this.props = props;
        this.service = this.loader(this.props.servicePath);
        this.registerController();
        this.registerRouter();
    }
    private registerRouter() {
        const routerMap: any = this.loader(this.props.routerPath);
        Object.getOwnPropertyNames(routerMap).map(f => {
            const routerObj = routerMap[f](this.controller);
            Object.getOwnPropertyNames(routerObj).map(r => {
                const [method, path] = r.split(' ');
                this.route[method.toLowerCase()](path, routerObj[r].bind(this.service));
            });
        });
    }
    private registerController() {
        const controllerMap: any = this.loader(this.props.controllerPath);
        const me = this;
        Object.getOwnPropertyNames(controllerMap).map(f => {
            Object.defineProperty(this.controller, f, {
                get() {
                    return controllerMap[f](me.service);
                }
            });
        });
    }
    private loader(path: string): object|void {
        const fileMap = scanFileName(path);
        let result: any = {};
        for (let i = 0, _len = fileMap.length; i < _len; i++) {
            const { absolutePath, filename } = fileMap[i];
            Object.defineProperty(result, (filename as string), {
                get() {
                    return require((absolutePath as string)).default;
                }
            });
        }
        return result;
    }
}
